package com.example.demo.config;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.dao.SysuserMapper;
import com.example.demo.domain.Sys_permission;
import com.example.demo.domain.Sysuser;
import com.example.demo.services.LoginService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
public class LoginResources {
	
	private static Logger logger = Logger.getLogger(LoginResources.class);

    @Autowired
    private LoginService loginService;
    @Autowired
    private SysuserMapper sysuserMapper;

    //退出的时候是get请求，主要是用于退出
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public ModelAndView login(){
    	return new ModelAndView("login");
    }

    //post登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(HttpServletRequest request, HttpServletResponse response, @RequestBody Map map) throws Exception{
    	String message = "0";
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                map.get("username").toString(),
                DigestUtils.md5DigestAsHex(((String) map.get("password")).getBytes()));
        //进行验证，这里可以捕获异常，然后返回对应信息
        try {
        	//查询用户名称
            Sysuser sysuser = sysuserMapper.findByName(map.get("username").toString());
            //判定用户是否正在使用
        	if(sysuser.getIs_delete() == 1) {
            	//返回认证接口
            	subject.login(usernamePasswordToken);
            	subject.getSession().setTimeout(-10001);
        	} else {
        		message = "3";	
        	}
        }catch (Exception e) {
        	System.out.println(e.toString());
        	if(e instanceof UnknownAccountException) {
        		message = "2";	//2代表用户名不存在
        	}else {
        		message = "1";//1代表其他错误，统一为账号或密码错误
        	}
        }	
        return message;
    }

    @RequestMapping(value = "/index")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	ModelAndView mv = new ModelAndView("index");
    	
    	//从会话中取出用户信息
    	Object username = SecurityUtils.getSubject().getPrincipal();
    	//查询用户名称
        Sysuser sysuser = sysuserMapper.findByName(username.toString());
        //通过用户名称查询用户权限模块信息
    	if(sysuser.getUsername() != null && !"".equals(sysuser.getUsername())) {
        	List<Sys_permission> sys_permission= loginService.queryLeftModel(sysuser.getUsername());
        	mv.addObject("sys_permission", JSONArray.fromObject(sys_permission));
        	mv.addObject("sysuser",JSONObject.fromObject(sysuser));
    	}
        return mv;
    }

    //登出
    @RequestMapping(value = "/logout")
    public ModelAndView logout(){
    	Subject subject = SecurityUtils.getSubject();
    	subject.logout();
    	return new ModelAndView("login");
    }
    
  //登出
    @RequestMapping(value = "/register")
    public ModelAndView register(){
    	return new ModelAndView("register");
    }

    //错误页面展示
    @RequestMapping(value = "/error",method = RequestMethod.POST)
    public ModelAndView error(){
    	return new ModelAndView("error");
    }

    //数据初始化
    @RequestMapping(value = "/addUser")
    public String addUser(@RequestBody Map<String,Object> map){
        return "addUser is ok! \n";
    }

    //角色初始化
    @RequestMapping(value = "/addRole")
    public String addRole(@RequestBody Map<String,Object> map){
        return "addRole is ok! \n";
    }

    //注解的使用
    @RequiresRoles("admin")
    @RequiresPermissions("create")
    @RequestMapping(value = "/create")
    public String create(){
        return "Create success!";
    }
}